package com.vhans.db.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vhans.core.domain.Correlation;
import com.vhans.core.domain.Storage;
import com.vhans.core.utils.BeanCopyUtils;
import com.vhans.db.mapper.CorrelationMapper;
import com.vhans.db.mapper.StorageMapper;
import com.vhans.db.model.dto.correlation.CorrelationDTO;
import com.vhans.db.model.vo.correlation.PurchasedInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 专门用来插入关联id
 * @author vhans
 */
@Service
public class CorrelationService {

    @Autowired
    private CorrelationMapper correlationMapper;

    @Autowired
    private StorageMapper storageMapper;

    /**
     * 插入关联消息id
     * @param correlation 关联id消息
     * @return 影响行
     */
    public int insertCorrelation(CorrelationDTO correlation) {
        int userId = StpUtil.getLoginIdAsInt();
        Correlation newCorrelation = BeanCopyUtils.copyBean(correlation, Correlation.class);
        newCorrelation.setUserId(userId);
        return correlationMapper.insert(newCorrelation);
    }

    /**
     * 获取已购买产品信息
     */
    public List<PurchasedInfo> getPurchasedInfo() {
        int userId = StpUtil.getLoginIdAsInt();
        List<PurchasedInfo> purchasedInfo = correlationMapper.getPurchasedInfo(userId);
        // 查询存储信息
        purchasedInfo.forEach(item -> {
            List<Integer> sIds = Arrays.stream(item.getStorageIds().split(",")).map(Integer::parseInt).toList();
            List<Storage> storages = storageMapper.selectList(new LambdaQueryWrapper<Storage>()
                    .select(Storage::getId, Storage::getDiscType, Storage::getType, Storage::getCapacity)
                    .in(Storage::getId, sIds));
            System.out.println(storages);
            item.setStorages(storages);
        });
        return purchasedInfo;
    }
}
